package concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 26029
 * @date 2025/4/21
 * @description
 */
public class LearnConcurrent {
    public static void main(String[] args) throws InterruptedException {
        final int threadSize = 500;
        ThreadUnsafe example = new ThreadUnsafe();
        // 一个同步工具类，初始化为 500，用于让主线程等待 500 个子线程全部执行完再继续。
        final CountDownLatch countDownLatch = new CountDownLatch(threadSize);
        // 线程池，创建一个 缓存线程池，可以自动扩展线程数量。
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < threadSize; i++) {
            executorService.execute(() -> {
                example.add();
                countDownLatch.countDown();
            });
        }
        // await() 会让主线程 阻塞等待，直到所有线程都执行完（即 500 次 countDown() 完成）
        countDownLatch.await();
        // 然后关闭线程池
        executorService.shutdown();

        System.out.println(example.getCount());
    }
}

class ThreadUnsafe{
    private int count = 0;

    public void add() {
        count++;
    }

    public int getCount() {
        return count;
    }
}